<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        class="filter-item"
        placeholder="输入关键字进行过滤"
        v-model="listQuery.keyword"
        style="width: 30%"
      >
      </el-input>
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"-->
      <!--      />-->
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">-->
      <!--        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150" align="center" label="标题">
        <template slot-scope="scope">
<!--          <router-link :to="'/company/excel?cid='+scope.row.id" class="link-type">-->
          <span>{{ scope.row.title }}</span>
<!--          </router-link>-->
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

      <el-table-column min-width="80" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="changeStatus($event,scope.row.id)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="发布日期">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left"
               style="width: 80%; margin-left:10%;"
      >
        <article-detail :is-edit="false" :post-form="temp"/>

<!--        <el-form-item label="图标">-->
<!--          <el-upload-->
<!--            class="avatar-uploader"-->
<!--            action="/api/upload/image"-->
<!--            :show-file-list="false"-->
<!--            :on-success="handleAvatarSuccess"-->
<!--            :before-upload="beforeAvatarUpload"-->
<!--          >-->
<!--            <el-image v-if="imageUrl" :src="imageUrl+'?rondom='+ Math.ceil(Math.random()*5)" class="avatar" width="100%"-->
<!--                      fit="contain"-->
<!--            ></el-image>-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, changeStatus, create, del } from '@/api/message'
// import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import ArticleDetail from './components/ArticleDetail'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination

export default {
  name: 'MessageList',
  components: { Pagination, ArticleDetail },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      dialogBannerVisible: false,
      showBannerUrl:'',
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: ''
      },
      temp: {
        id: undefined,
        numbers:0,
        name: '',
        status:0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      imageUrl:'',
      activeName:'second',
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
  },
  methods: {
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes())
    },
    setCheckedNodes(row) {
      this.$refs.tree.setCheckedNodes(row)
    },
    handleClick(){

    },
    changeStatus(val,id){
      changeStatus(val,id).then(response =>{
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
      })
    },
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialogFormVisible = false
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              if(this.temp.type == 1){
                 this.getPcate()
              }
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row) // copy obj
      this.imageUrl = this.temp.thumb
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        numbers:0,
        name: '',
        status:0
      }
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.imageUrl = res.data.thumb
        this.temp.url = res.data.url
        this.temp.thumb = res.data.thumb
        this.$notify({
          title: '消息',
          type: 'success',
          message: '上传成功',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '消息',
          type: 'error',
          message: '上传失败',
          duration: 2000
        })
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isLt10M
      //  return isJPG && isLt2M;
    },
    showBanner(url) {
      this.showBannerUrl = url
      this.dialogBannerVisible = true
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
